import { ref, watch } from "vue";
import { useFullscreen } from "@vueuse/core";

// Use Vue's ref system to manage fullscreen state
const { isFullscreen, toggle } = useFullscreen(ref(document.documentElement));

// Export fullscreen state
export { isFullscreen };

// Reference to the element that is currently fullscreen
const fullScreenElementRef: Ref<HTMLElement | null> = ref(null);

// Toggle fullscreen for a given element
export const toggleFullScreen = (el: HTMLElement | null): void => {
  if (!el || !(el instanceof HTMLElement)) {
    console.warn("Provided element is not a valid HTMLElement");
    return;
  }

  // If currently in fullscreen and the same element is clicked, exit fullscreen
  if (fullScreenElementRef.value === el && isFullscreen.value) {
    toggle();
    el.classList.remove("fullscreen-el");
    fullScreenElementRef.value = null; // Clear reference since we're exiting fullscreen
  } else {
    if (fullScreenElementRef.value) {
      fullScreenElementRef.value.classList.remove("fullscreen-el");
    }
    toggle();
    el.classList.add("fullscreen-el");
    fullScreenElementRef.value = el;
  }
};

// Watch for ESC key fullscreen exit
watch(isFullscreen, newVal => {
  if (!newVal && fullScreenElementRef.value) {
    fullScreenElementRef.value.classList.remove("fullscreen-el");
    fullScreenElementRef.value = null;
  }
});

// Check if the given element is currently fullscreen
export const getElIsFullScreen = (el: HTMLElement | null): boolean => {
  return fullScreenElementRef.value === el && isFullscreen.value;
};
